# 创建时间:2023/2/10 23:19
# 创建人:天霄
# 计划 :SenjoTwintail
# 文件 :do_plist.py
# 基于 Python 3.8.2
# ========================================
# 本脚本并未用于游戏，仅用于按plist切割图片，另存为切割后的若干图片便于查看，查看后可删除。
# ========================================
from vars import *
import pathlib
from xml.etree import ElementTree
from PIL import Image
from PIL.PngImagePlugin import PngImageFile
import plistlib


def plist2dict(plist_filename):
    """将plist转为dict，标签为类型，标签值为key或value"""
    # """请直接使用biplist.readPlist()"""
    def _tree2dict(tree: ElementTree.Element):
        d = {}
        for index, item in enumerate(tree):
            # print(index, item)
            if item.tag == 'key':
                if tree[index + 1].tag == 'string':
                    d[item.text] = tree[index + 1].text
                elif tree[index + 1].tag == 'real':
                    d[item.text] = float(tree[index + 1].text)
                elif tree[index + 1].tag == 'integer':
                    d[item.text] = int(tree[index + 1].text)
                elif tree[index + 1].tag == 'true':
                    d[item.text] = True
                elif tree[index + 1].tag == 'false':
                    d[item.text] = False
                elif tree[index + 1].tag == 'dict':
                    d[item.text] = _tree2dict(tree[index + 1])
                else:
                    print(f'存在不明类型标签：{tree[index + 1].tag}')
                    d[item.text] = str(tree[index + 1].text)
            elif item.tag == 'dict' and not d:
                d = _tree2dict(item)
        return d
    return _tree2dict(ElementTree.parse(plist_filename).getroot())


def gen_png_from_plist(rootdir: pathlib.Path, plist_filename: pathlib.Path, png_filename: pathlib.Path):
    """根据plist配置生成图片

    :param rootdir: 生成图片的拼接根目录
    :param plist_filename: plist文件路径
    :param png_filename: png文件路径
    :return:
    """
    if not all((plist_filename.exists(), png_filename.exists())):
        print("文件不存在！")
    big_image = Image.open(png_filename)
    # print(type(big_image))
    # plist_dict = tree_to_dict(plist_filename)
    with open(plist_filename, 'rb') as f:
        plist_dict = plistlib.load(f)

    print(plist_dict)
    outfile_list = list()
    to_list = lambda x: list(map(int, x.replace('{', '').replace('}', '').split(',')))
    for k, v in plist_dict['frames'].items():
        rectlist = to_list(v['frame'])
        angle = 0
        if v['rotated']:
            angle = 90
            rectlist[2], rectlist[3] = rectlist[3], rectlist[2]
        width = rectlist[2]
        height = rectlist[3]
        box = (int(rectlist[0]),
            int(rectlist[1]),
            int(rectlist[0]) + width,
            int(rectlist[1]) + height)
        sizelist = to_list(v['sourceSize'])
        # center = to_list(v['offset'])
        rect_on_big = big_image.crop(tuple(box))
        # rect_on_big = rect_on_big.rotate(angle)  # 旋转

        # result_image = Image.new('RGBA', sizelist, (0, 0, 0, 0))  # 改变尺寸
        # result_box = (
        #     (sizelist[0] - width) // 2,
        #     (sizelist[1] - height) // 2,
        #     (sizelist[0] + width) // 2,
        #     (sizelist[1] + height) // 2
        # )
        # print(rect_on_big, result_box)
        # result_image.paste(rect_on_big, result_box, mask=0)

        if not rootdir.exists():
            rootdir.mkdir()
        outfile = rootdir / k
        # result_image.save(outfile)
        if outfile.exists():
            print(f'存在同名文件【{outfile}】！取消生成！')
            for f in outfile_list:
                f.unlink()
            raise FileExistsError(f'存在同名文件【{outfile}】！')
        try:
            rect_on_big.save(outfile)
        except Exception as e:
            print(f'发生错误，[{outfile=}]。错误：\n{e}')
            raise
        outfile_list.append(outfile)
        print(f'-->已生成文件{outfile}')
    return outfile_list


def valuesprint(values: list, name):
    for v in values:
        file = v.stem
        print(f"{file} = {name}['{file}']  # ")


if __name__ == '__main__':
    # ==============================>>
    # filename = sys.argv[1]
    from Api import uiApi
    rootdir = CONST.PATH.ASSETS_ROOT / 'res'

    # png_filename, plist_filename = uiApi.getUiPathPlist('favorlayer2')
    png_filename, plist_filename = uiApi.getEffectPathPlist('favorscoreupeffect')
    outfiles = gen_png_from_plist(rootdir, plist_filename, png_filename)
    valuesprint(outfiles, 'favorscoreupeffect')
    delete_flag = input('\n——>是否要删除这些文件？（y-是，其他-否）')
    if delete_flag.lower().strip() == 'y':
        for o in outfiles:
            o.unlink()
        print('已删除。')




